<template>
	<view class="wrapper">
		<view class="flex flex-between golf-userTitle">
			<view></view>
			<view class="golf-usernum">{{nicknameStr}}</view>
			<view class="golf-set" @click="gameSetting">设置</view>
		</view>

		<view class="golf-scoreContent text-center">
			<tabsControl :current="current" :values="items" @clickItem="onClickItem" style-type="button" active-color="#0fd762">
				<view slot="refresh" @click="refresh">
					<image src="../../static/image/refresh.png" mode="" style="width: 22rpx;height: 22rpx;"></image>
					<text style="color: rgba(87,137,254,1);">刷新数据</text>
				</view>
			</tabsControl>
			<text class="golf-rule">比赛规则:{{golfData.tournamentRule === 0 ? '一般规则' : (golfData.tournamentRule === 1 ? '大流氓' : '小流氓')}}</text>
			<view class="flex flex-between align-center golf-scoreInfo">
				<view>
					<button v-if="type === 1" type="default" :plain='true' open-type="share" class="golf-shareText"><image class="golf-share" src="/static/image/share.png"></image></button>
					<text v-if="type === 1" class="golf-shareText">围观邀请</text>
				</view>
				<view class="golf-siteInfo">
					<view>四川成都国际场</view>
					<view class="golf-date">周{{"日一二三四五六".charAt(new Date(golfData.teeTime.split(' ')[0]).getDay())}} {{golfData.teeTime}}</view>
				</view>
				<view @click="toScoreDetail">
					<image class="golf-scoring" src="/static/image/date.png"></image>
					<text class="golf-shareText">计分卡</text>
				</view>
			</view>
			<view class="golf-scoringPk">
				<view v-if="current === 0">
					<p-table :tableData="tableData" :firstHole="firstHole" :scoreHole="scoreHole" @setCore="setCore" align="center"></p-table>
				</view>
				<view v-show="current === 1">
					<ballScoreItem :golfTournamentId="golfTournamentId" ref="child" :tournamentStatus="tournamentStatus" :type="type"  ></ballScoreItem>
				</view>
			</view>
		</view>
		<view class="getAuth" v-if="authBool">
			<button type="primary" open-type="getUserInfo" @getuserinfo='getuserinfo' @click="getUser">点击授权</button>
		</view>
		<button class="playGame" type="primary" @click="startPlay" v-if="type ===1 && tournamentStatus < 2">开球</button>
	</view>
</template>

<script>
	import tabsControl from "@/components/tabs/tabs.vue"
	import pTable from '@/components/portrait-table/portrait-table.vue'
	import ballScoreItem from '@/components/ballScoreItem/ballScoreItem.vue'
	export default {
		components: {
			tabsControl,
			pTable,
			ballScoreItem
		},
		props: {},
		data() {
			return {
				authBool: true,
				type: 0, // 当前身份
				firstHole: '',
				nicknameStr: '',
				golfTournamentId: '',
				tournamentStatus: 0,
				items: ['计分卡', 'PK'],
				current: 0,
				scoreHole: [],
				golfData: {
					teeTime: '',
					tournamentRule: ''
				},
				tableData: [],
				showTabs:1,
				
			}
		},
		watch: {},
		computed: {},
		onShareAppMessage(res) {
		    if (res.from === 'button') {// 来自页面内分享按钮
				console.log('分享')
				return {
				  title: '快来观战吧！',
				  path: '/pages/onlooker/onlooker?golfTournamentId=' + this.golfTournamentId
				}
		    }
		 },
		methods: {
			refresh () {
				this.getScoreCard()
				this.handleClick()
			},
			getUser () {
				new Promise(resolve => {
					uni.getProvider({ //获取设备权限信息
						service: 'oauth',
						success: res => {
							resolve(res);
						}
					})
				}).then(res => {
					console.log('设备权限信息', res)
					
					uni.showLoading({
						title: '正在加载中'
					})
					return new Promise(resolve => {
						uni.login({ //登录加载获取code
							provider: `${res.provider[res.provider.length-1]}`,
							success: res => {
								resolve(res);
							}
						});
					}).then(loginCode => {
						console.log('登录code', res)
						uni.hideLoading()
						return new Promise(resolve => {
							this.$api.login.openIdRequest({ //获取openid
								data: {
									code: loginCode.code
								},
								success: res => {
									resolve(res);
									console.log('获取openid', res.data.data.openid)
									this.openId = res.data.data.openid
									uni.setStorage({
										key: 'openId',
										data: res.data.data.openid,
									});
									this.$store.commit('openId', res.data.data.openid)
								}
							})
						})
					})
				})
			},
			getuserinfo() {
				new Promise(resolve => {
					uni.getUserInfo({ //获取用户信息
						success: res => {
							resolve({
								nickName: res.userInfo.nickName, //昵称
								avatar: res.userInfo.avatarUrl, //头像
								sex: res.userInfo.gender, //性别 0未填 1 男性 2女性
							});
						}
					})
				}).then(resUserInfo => {
					uni.setStorage({
						key: 'userInfo',
						data: resUserInfo,
					});
					this.$store.commit('userInfo', resUserInfo) //保存至Vuex内存
					return new Promise(async resolve => {
						console.log(1111, uni.getStorageSync('openId'))
						const {
							data: res
						} = await this.$api.login.loginRequest({
							data: {
								avatar: resUserInfo.avatar,
								creatorOpenId: uni.getStorageSync('openId'),
								nickname: resUserInfo.nickName,
								sex: resUserInfo.sex,
								openId: uni.getStorageSync('openId'),
								updatorOpenId: uni.getStorageSync('openId'),
							},
						})
						if (res.code === 0) {
							uni.setStorage({ //高尔夫球员ID存入本地
								key: 'golfGalleryId',
								data: res.data.golfGalleryId,
							});
							this.authBool = false
							// 这里进行绑定add
							this.bindGall()
						}
					})
				})

			},
			handleClick(){
				this.$refs.child.getPkList();
				this.$refs.child.getPkInfo();
				this.$refs.child.getLikeList()
				},
			toScoreDetail(){
				uni.navigateTo({
					url: '/pages/addPk/scoreDetail?golfTournamentId=' + this.golfTournamentId 
				})
			},
			setCore (msg) {
				console.log('core:', this.tournamentStatus, this.type)
				if (this.tournamentStatus !== 2) {
					uni.showToast({
					    title: '当前球局未开始',
					    duration: 2000
					});
					return
				}
				if (msg.holeNo < 1) {
					return
				}
				uni.navigateTo({
					url: '/pages/setScore/setScore?golfTournamentId=' + this.golfTournamentId + '&holeNo=' + msg.holeNo + '&par=' + msg.par
				})
			},
			gameSetting () {
				uni.showActionSheet({
					itemList: ['修改球局','取消球局'],
					success: async (res) => {
						if (res.tapIndex === 0) {
							uni.navigateTo({
								url: '/pages/modification/modification?golfTournamentId=' + this.golfTournamentId + '&golfData=' + JSON.stringify(this.golfData)
							})
						} else if (res.tapIndex === 1) {
							const {
								data: res1
							} = await this.$api.score.removeGame({
								data: {
									golfTournamentId: this.golfTournamentId
								}
							})
							if (res1.code === 0) {
								uni.showToast({
								    title: '取消成功',
								    duration: 2000
								});
								uni.switchTab({
								    url: '/pages/index/index'
								});
							}
						}
					}
				})
			},
			bindGall() {
				this.$api.match.bindGaller({
					data: {
						tournamentIdentity: 1,
						isOrganizer: 0,
						golfTournamentId: this.golfTournamentId,
						golfGalleryId: uni.getStorageSync('golfGalleryId'),
						tee: 3,
						kickoffOrder: 0,
					}
				}).then(res => {
					if (res.data.code == 0) {
						uni.setStorage({
							key: "golfTournamentGalleryId",
							data: res.data.data.golfTournamentGalleryId
						})
						this.getScoreCard()
					}
					console.log(res)
				})
			},
			async getScoreCard() {
				const {
					data: res
				} = await this.$api.pTable.scoreCard({
					data: {
						golfTournamentId: this.golfTournamentId
					}
				})
				if (res.code === 0) {
					this.tableData = res.data.golferScoreModelList
					this.tournamentStatus = Number(res.data.golfTournament.tournamentStatus)
					this.firstHole = res.data.golfTournament.firstHole
					let arr = []
					for (let val of this.tableData[0].holeScoreList) {
						arr.push({holeNo: val.holeNo,par: val.par})
					}
					this.scoreHole = arr
					// 获取昵称组合
					let str = []
					for (let val of this.tableData) {
						str.push(val.nickname)
					}
					this.nicknameStr = str.join(',')
					this.golfData.teeTime = res.data.golfTournament.teeTime
					this.golfData.tournamentRule = res.data.golfTournament.tournamentRule
					// this.golfListNull = res.data.records
				}
			},
			onClickItem(e) {
				this.handleClick()
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex;
				}
			},
			startPlay () {
				uni.showModal({
				    title: '提示',
				    content: '开球后不能再添加pk和点赞,确认开球吗？',
				    success: async (res) => {
				        if (res.confirm) {
							const {
								data: res
							} = await this.$api.score.startPlay({
								data: {
									golfTournamentId: this.golfTournamentId
								}
							})
							if (res.code === 0) {
								this.tournamentStatus = 2
								uni.showToast({
									title: '开球成功',
									duration: 2000
								});
							}
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
			},
		},
		created() {},
		mounted() {},
		onLoad(option) {
			this.golfTournamentId = option.golfTournamentId
			this.type = Number(option.type) // 1.组织 2.球员
			// if(this.golfTournamentId){
			// }
			let that = this
			uni.getSetting({
				success(res) {
					console.log("授权：", that);
					if (!res.authSetting['scope.userInfo']) {
						//这里调用授权
						console.log("当前未授权");
						that.authBool = true
					} else {
						that.authBool = false
						if (that.type === 2) {
							that.bindGall()
						}
					}
				}
			})
		},
		onShow () {
			if(this.golfTournamentId){
			this.handleClick()
			}
			this.getScoreCard()
		}
	}
</script>
<style scoped lang="less">
	
	.wrapper {
		overflow: hidden;
	}

	.getAuth {
		width: 100%;
		height: 100vh;
		position: absolute;
		top: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.5);

		>button {
			position: absolute;
			bottom: 0;
			width: 100%;
		}
	}
	
	.golf-usernum {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 600rpx;
		text-align: center;
	}
	.playGame {
		position: fixed;
		bottom: 0;
		width: 100%;
	}
	.golf-userTitle {
		padding: 18rpx 24rpx;
		background-color: #fff;
	}

	.golf-set {
		font-size: 28rpx;
		font-weight: 400;
		color: #999;
	}

	.golf-rule {
		display: block;
		font-size: 24rpx;
		color: #999;
		margin-bottom: 30rpx;
	}

	.golf-scoreContent {
		margin: 0 auto;
	}

	.golf-scoreInfo {
		padding: 0 24rpx;
	}

	.golf-share,
	.golf-scoring {
		width: 48rpx;
		height: 48rpx;
	}

	.golf-shareText {
		display: block;
		font-size: 24rpx;
		color: #999;
		border: none !important;
	}

	.golf-siteInfo .golf-date {
		font-size: 26rpx;
		color: #333;
	}

	.golf-scoreTable {
		margin-top: 24rpx;
	}

	.golf-scoringPk {
		padding-left: 24rpx;
	}
</style>
